package com.hatic.contract;

import java.util.Map;

import org.jxstar.dao.DaoParam;
import org.jxstar.service.BusinessObject;

import com.hatic.process.ProjectMoneyBO;

/**
 * 合同变更金额更新处理。
 *
 * @author TonyTan
 * @version 1.0, 2011-10-29
 */
public class ContractChgBO extends BusinessObject {
	private static final long serialVersionUID = 1L;

	public String preAudit(String[] dataIds) {
		if (dataIds == null || dataIds.length == 0) {
			setMessage("没有选择合同记录！");
			return _returnFaild;
		}
		
		for (int i = 0, n = dataIds.length; i < n; i++) {
			if (!updateMoney(dataIds[i])) {
				return _returnFaild;
			}
		}
		
		return _returnSuccess;
	}
	
	//检查合同金额是否超预算，同时要更新合同金额
	private boolean updateMoney(String dataId) {
		Map<String,String> mpData = queryContract(dataId);
		
		String projectId = mpData.get("project_id");
		String contractId = mpData.get("contract_id");
		String oldmoney = mpData.get("before_money");
		String newmoney = mpData.get("after_money");
		
		double oldnum = Double.parseDouble(oldmoney);
		double newnum = Double.parseDouble(newmoney);
		_log.showDebug("---------项目ID=" + projectId + "; 新合同金额：" + newmoney);
		
		if (newnum <= 0) {
			setMessage("变更后的合同金额不能为零！");
			return false;
		}
		
		if (!updateContract(contractId, newmoney)) {
			setMessage("更新变更后的合同金额出错！");
			return false;
		}
		
		//变更后增加的合同金额
		double diffnum = newnum - oldnum;
		
		//项目ID为空时，返回TRUE
		if(projectId == null || projectId.length() == 0) return true;
		
		//检查合同金额是否超出项目批复金额
		ProjectMoneyBO projectbo = new ProjectMoneyBO();
		boolean checked = projectbo.checkContractMoney(projectId, diffnum);
		if (!checked) {
			String message = projectbo.getMessage();
			if (message == null || message.length() == 0) {
				message = "检查合同金额是否超额时出错！";
			}
			setMessage(message);
			return false;
		}
		
		//更新项目、投资计划的合同总金额
		checked = projectbo.addContractMoney(projectId, diffnum);
		if (!checked) {
			String message = projectbo.getMessage();
			if (message == null || message.length() == 0) {
				message = "更新项目中的合同金额出错！";
			}
			setMessage(message);
			return false;
		}
		
		return true;
	}
	
	//更新变更后的合同金额
	private boolean updateContract(String contractId, String money) {
		String sql = "update contract set contract_money = ? where contract_id = ?";
		DaoParam param = _dao.createParam(sql);
		param.addDoubleValue(money);
		param.addStringValue(contractId);
		
		return _dao.update(param);
	}
	
	//查询合同变更信息
	private Map<String,String> queryContract(String dataId) {
		String sql = "select project_id, contract_id, before_money, after_money " +
				"from contract_change where change_id = ?";
		DaoParam param = _dao.createParam(sql);
		param.addStringValue(dataId);
		
		return _dao.queryMap(param);
	}
}
